extends IBasicComponent


class_name StateComponent
"""
适配对象的完成状态逻辑
"""


## 状态切换时的通知
signal event_state_changed(cmpt: StateComponent, prev: int, next: int, duration: float)


## 适配的对象
@export var wrapper: Node = null


"""
func on_state(state: int, current: int, state_duration: float) -> void:
    pass

func update_state(prev: int, state: int, delta: float, state_duration: float) -> int:
    return state
"""


## 当前状态
var __state: int = 0
## 上一个状态
var __prev_state: int = 0
## 状态持续时间
var __state_duration: float = 0


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "wrapper": IComponent.find_parent.bind(self, func(x): return x is Node, wrapper),
    }, super.__check_exports())

## 状态切换
func switch(next: int) -> void:
    event_state_changed.emit(self, __prev_state, next, __state_duration)

    wrapper.on_state(__state, next, __state_duration)
    __prev_state = __state
    __state = next
    __state_duration = 0

func _physics_process(delta: float) -> void:
    __state_duration += delta
    # 迭代状态
    var next: int = wrapper.update_state(__prev_state, __state, delta, __state_duration)
    if __state != next:
        switch(next)
